from django.contrib.auth import authenticate, login
from django.forms import modelform_factory
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
# Create your views here.
from itmopets.models import Profile, Pet
from accounts.forms import NewUserCreationForm, EditProfileForm, ProfileForm, PetForm


class ItmopetsUserCreationForm(NewUserCreationForm):
    def __init__(self, *args, **kwargs):
        super(NewUserCreationForm, self).__init__(*args, **kwargs)
        print(self.fields)
        self.fields['username'].help_text = ''
        self.fields['password1'].help_text = ''
        self.fields['password2'].help_text = 'Введите пароль снова, чтобы проверить правильность ввода'
        self.fields['username'].label = 'Логин'
        self.fields['password1'].label = 'Пароль'
        self.fields['password2'].label = 'Повторите пароль'


def indexView(request):
    return render(request, 'index.html')


@login_required()
def dashboardView(request):
    return render(request, 'dashboard.html')

def update_user_data(user):
    Profile.objects.update_or_create(user=user, defaults={'contact': user.profile.contact, 'birthdate': user.profile.date_of_birth},)


def registerView(request):
    if request.method == "POST":
        form = NewUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.profile.contact = form.cleaned_data.get('contact')
            user.profile.date_of_birth = form.cleaned_data.get('birthdate')
            update_user_data(user)
            user.save()
            raw_password = form.cleaned_data.get('password1')

            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
        return redirect('home')
    else:
        form = NewUserCreationForm()
    return render(request,'registration/register.html',{'form':form})


@login_required
def edit_profile(request):
    if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)

        if form.is_valid() and profile_form.is_valid():
            user_form = form.save()
            custom_form = profile_form.save(False)
            custom_form.user = user_form
            custom_form.save()
            return redirect('home')
    else:
        form = EditProfileForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
        args = {}
        # args.update(csrf(request))
        args['form'] = form
        args['profile_form'] = profile_form
        return render(request, 'registration/edit_profile.html', args)


@login_required
def view_profile(request):
    args = {'user': request.user, 'profile': request.user.profile}
    return render(request, 'registration/view_profile.html', args)

@login_required
def view_pet(request, id):
    return render(request, 'registration/view_pet.html', {"pet": Pet.objects.get(id=id)})

@login_required
def add_pet(request):
    if request.method == 'POST':
        form = PetForm(request.user, request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = PetForm(request.user)
    return render(request, 'registration/add_pet.html', {'form': form})

@login_required
def edit_pet(request, id):
    if request.method == 'POST':
        form = PetForm(request.user, request.POST, instance=Pet.objects.get(id=id))
        if form.is_valid():
            form.save()
            return redirect('view_pet', id=id)
    else:
        form = PetForm(request.user, instance=Pet.objects.get(id=id))
        args = {'form': form}
        return render(request, 'registration/edit_profile.html', args)

